package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 排除微信请求
     */
    public boolean isExcludeRequest() {
        // 尝试获取当前请求上下文
        HttpServletRequest request = getCurrentRequest();
        if (request == null) {
            return false;
        }
        String requestURI = request.getRequestURI();
        return requestURI.startsWith("/member");
    }

    @Override
    public void insertFill(MetaObject metaObject) {

        if(isExcludeRequest())
        {
            this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getLoginUserId()));
        }
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(isExcludeRequest())
        {
            this.setFieldValByName("updateBy", String.valueOf(getLoginUserId()), metaObject);
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    /**
     * 获取当前HTTP请求上下文，如果不存在则返回null
     */
    private HttpServletRequest getCurrentRequest() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return attributes != null ? attributes.getRequest() : null;
        } catch (Exception e) {
            // 在非Web上下文（如定时任务）中会抛出异常，此时返回null
            return null;
        }
    }

    public Long getLoginUserId() {
        // 获取到当前登录人的信息
        try {
            // 首先检查是否在Web环境中
            if (getCurrentRequest() == null) {
                // 非Web环境（如定时任务）返回系统用户ID
                return 1L;
            }

            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (ObjectUtils.isNotEmpty(loginUser)) {
                return loginUser.getUserId();
            }
            return 1L;
        } catch (Exception e) {
            // 发生任何异常都返回系统用户ID
            return 1L;
        }
    }
}
